<template>
  <el-container>
    <el-header>
      <p>组织机构管理</p>
    </el-header>
    <el-main>
      <el-row class="btn-group">
        <el-button class="btn" @click="handleCreateOrg">
          <span>增加</span><i class="el-icon-plus"></i>
        </el-button>
        <!--<el-button class="btn" @click="handleUpdateOrg">-->
          <!--<span>编辑</span><i class="el-icon-edit"></i>-->
        <!--</el-button>-->
        <el-button class="btn" @click="handleDeleteOrg">
          <span>删除</span><i class="el-icon-delete"></i>
        </el-button>
        <el-button class="btn" @click="handleDownloadOrg">
          <span>导出</span><i class="el-icon-download"></i>
        </el-button>
      </el-row>
      <el-table :data="dataList" v-loading="listLoading" element-loading-text="给我一点时间"
                highlight-current-row stripe
                style="width: 100%" ref="orgTable" @selection-change="handleSelectChangeOrg">
        <el-table-column fixed type="selection" width="50"></el-table-column>
        <el-table-column fixed sortable align="center" label="单位编号" width="180" prop="orgbh">
          <template slot-scope="scope">
            <span>{{scope.row.orgbh}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位名称" width="150" sortable prop="orgname">
          <template slot-scope="scope">
            <span>{{scope.row.orgname}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="上级单位" width="150" sortable prop="parentorgname">
          <template slot-scope="scope">
            <span>{{scope.row.parentorgname}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="机构类型" width="150" sortable prop="orgtypename">
          <template slot-scope="scope">
            <span>{{scope.row.orgtypename}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位级别" width="150" sortable prop="orglevelname">
          <template slot-scope="scope">
            <span>{{scope.row.orglevelname}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="负责人" width="150" sortable prop="headername">
          <template slot-scope="scope">
            <span>{{scope.row.headername}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="电话号码" width="150" sortable prop="orgtel">
          <template slot-scope="scope">
            <span>{{scope.row.orgtel}}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" width="100" label="操作">
          <template slot-scope="scope">
            <el-dropdown trigger="click" @command="handleCommand">
              <el-button class="btn-drop-down" @click="selectRow(scope.row)">
                <i class="el-icon-arrow-down"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="del">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

    </el-main>
    <el-footer>
      <el-pagination background @size-change="handleSizeChangeOrg" @current-change="handleCurrentChangeOrg"
                     :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-footer>
    <el-dialog :title="dialogText[dialogStatusOrg]" :visible.sync="dialogCreateVisible" center>
      <el-form ref="createForm" :rules="rulesOrg" :model="tempOrg" label-position="left" label-width="100px"
               style='width: 400px; margin-left:50px;'>
        <el-form-item label="单位编号" prop="orgbh">
          <el-input clearable placeholder="请输入单位编号" v-model="tempOrg.orgbh"></el-input>
        </el-form-item>
        <el-form-item label="单位名称" prop="orgname">
          <el-input v-model="tempOrg.orgname" clearable placeholder="请输入单位名称"></el-input>
        </el-form-item>
        <el-form-item prop="parentorgname" label="上级单位">
          <el-input v-model="tempOrg.parentorgname" @click.native="handleSelectDwNameOrg" clearable  readonly
                    placeholder="上级单位"></el-input>
        </el-form-item>
        <el-form-item label="单位级别" prop="orglevel">
          <el-select v-model="tempOrg.orglevel" placeholder="请选择单位级别" style="width: 300px">
            <el-option v-for="item in orgLevels" :key="item.id" :value="item.id" :label="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机构类型" prop="orgtype">
          <el-select v-model="tempOrg.orgtype" placeholder="请选择机构类型" style="width: 300px">
            <el-option v-for="item in orgTypes" :key="item.id" :value="item.id" :label="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话号码" prop="orgtel">
          <el-input v-model="tempOrg.orgtel" clearable placeholder="请输入电话号码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateVisible = false" class="btn-search">取消</el-button>
        <el-button v-if="dialogStatusOrg=='create'" type="primary" @click="createDataOrg" class="btn-search">确定</el-button>
        <el-button v-else type="primary" @click="updateDataOrg" class="btn-search">确定</el-button>
      </div>
      <person-child-dialog-dw :dialogDwVisible.sync="dialogDwVisibleOrg"   @dwName="selectDwnameOrg" :dwType="0"></person-child-dialog-dw>
    </el-dialog>
  </el-container>
</template>

<script>
  /* eslint-disable */
  import {fetchListOrg, deleteListOrg, updateOrg, createOrg} from '@/api/organization/organization'
  import {selDictonary} from "../../../api/dictionary";
  import ElContainer from "element-ui/packages/container/src/main";
  import ElHeader from "element-ui/packages/header/src/main";
  import ElMain from "element-ui/packages/main/src/main";
  import PersonChildDialogDw from '../personChild/personChildDialogDw'

  export default {
    components: {
      ElMain,
      ElHeader,
      ElContainer,
      PersonChildDialogDw
    },
    name: 'org-table',
    props: ['searchList', 'listLoadingOrg'],
    watch: {
      searchList(val) {
        this.dataList = val.list
        this.total = val.count
      },
      listLoadingOrg(val) {
        this.listLoading = val
      }
    },
    created() {
      this.initData()
    },
    data() {
      return {
        listLoading: false,
        dialogDwVisibleOrg: false,
        dataList: [],
        selectList: [],
        total: 0,
        listQuery: {
          page: 1,
          limit: 20
        },
        dialogText: {create: '新增', update: '编辑'},
        dialogStatusOrg: '',
        dialogCreateVisible: false,
        tempOrg: {
          orgbh: '',
          orgno: '',
          orgname: '',
          orglevel: '',
          orgtel: '',
          parentorg: '',
          parentorgname: '', orgtype: '', header: '', headername: ''
        },
        orgLevels: [],
        orgTypes:[],
        // 规则
        rulesOrg: {
          orgbh: [{required: true, message: '请输入单位编号', trigger: 'blur'}],
          orgname: [{required: true, message: '请输入单位名称', trigger: 'blur'}],
          orglevel: [{required: true, message: '请输入单位级别', trigger: 'change'}],
          orgtype: [{required: true, message: '请选择机构类型', trigger: 'change'}],
          orgtel: [{pattern: /^[0-9]*$/, message: '请输入正确的电话号码', trigger: 'blur'}]
        }
      }
    },
    methods: {
      handleCreateOrg() {
        this.resetTemp()
        this.dialogCreateVisible = true
        this.dialogStatusOrg = 'create'
        this.$nextTick(() => {
          this.$refs['createForm'].clearValidate()
        })
      },
      handleUpdateOrg() {
        // if (this.selectList.length != 1) {
        //   this.$message({
        //     showClose: true,
        //     message: '请选择一条进行编辑',
        //     type: 'warning',
        //     duration: 2000
        //   });
        //   return
        // }
        this.dialogStatusOrg = 'update'
        // this.tempOrg = Object.assign({}, this.selectList[0]) // copy obj
        this.dialogCreateVisible = true
        this.$nextTick(() => {
          this.$refs['createForm'].clearValidate()
        })
      },
      handleDeleteOrg() {
        this.deleteOrg(this.selectList)
      },
      handleDownloadOrg() {
        this.downloadLoading = true
      },
      handleSelectChangeOrg(val) {
        this.selectList = val
      },
      handleSizeChangeOrg(val) {
        this.listQuery.limit = val
        this.$emit('handleSizeChangeOrg', val)
      },
      handleCurrentChangeOrg(val) {
        this.listQuery.page = val
        this.$emit('handleCurrentChangeOrg', val)
      },
      handleSelectDwNameOrg() {
        this.dialogDwVisibleOrg= true
      },
      selectDwnameOrg( val){
        this.tempOrg.parentorg=val.parentorg
        this.tempOrg.parentorgname=val.parentorgname
      },
      createDataOrg() {
        this.$refs['createForm'].validate((valid) => {
          if (valid) {
            createOrg(this.tempOrg).then(() => {
              // this.tempOrg.orgtypename=
              this.dataList.unshift(this.tempOrg)
              this.dialogCreateVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      updateDataOrg() {
        this.$refs['createForm'].validate((valid) => {
          if (valid) {
            updateOrg(this.tempOrg).then(() => {
              for (const v of this.dataList) {
                if (v.orgno === this.tempOrg.orgno) {
                  const index = this.dataList.indexOf(v)
                  console.log(this.tempOrg)
                  this.dataList.splice(index, 1, this.tempOrg)
                  break
                }
              }
              this.dialogCreateVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      initData() {
        selDictonary().then(res => {
          console.log(res)
          for (var item in res) {
            if (res[item].id == "orglevel") {
              this.orgLevels = res[item].comboboxDetailList
            }
            if(res[item].id=="orgtype"){
              this.orgTypes=res[item].comboboxDetailList
            }
          }
        })
      },
      handleCommand(val) {
        if (val == "edit") {
          this.handleUpdateOrg()
        } else if (val == "del") {
          let tempList = []
          tempList.push(this.tempOrg)
          this.deleteOrg(tempList)
        }
      },
      selectRow(val) {
        this.tempOrg = Object.assign({}, val) // copy obj
      },
      deleteOrg(val) {
        if (val.length) {
          this.$confirm('此操作将永久删除选中的记录,是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteListOrg(val).then(() => {
              for (const v of val) {
                let indexOf = this.dataList.indexOf(v);
                this.dataList.splice(indexOf, 1)
              }
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            },
              ()=>{
                this.$message({
                  type: 'error',
                  message: '删除失败',
                  duration: 2000
                })
              }
            )
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
              duration: 2000
            })
          })
        }
      },
      resetTemp() {
        this.tempOrg = {
          orgbh: '',
          orgno: '',
          orgname: '',
          orglevel: '',
          orgtel: '',
          parentorg: '',
          parentorgname: '', orgtype: '', header: '', headername: ''
        }
      }
    }
  }
</script>

<style scoped>
  .btn-group > .el-button span {
    display: none;
  }

  .btn-group > .el-button:hover {
    background-color: #409EFF;
  }

  .btn-group > .el-button:hover span {
    display: block;
  }

  .btn-group > .el-button:hover i {
    display: none;
  }
</style>
